from fastapi import APIRouter, Depends, HTTPException
from app.schemas.user import *
from app.schemas.response import success, success_list, error
from app.core.dependencies import get_db
from sqlalchemy.orm import Session
from app.services.impl.UserServiceImpl import *


router = APIRouter()


# 获取所有用户
@router.get("/")
async def read_users(db: Session = Depends(get_db)):
    users = user_crud.get_all(db)
    return success_list(users, len(users))


# 创建用户
@router.post("/")
async def create_user(user_in: UserCreate, db: Session = Depends(get_db)):
    user = user_crud.get_by_email(db, email=user_in.email)
    if user:
        return error("Email already registered", 400)

    created_user = user_crud.create(db, obj_in=user_in)
    return success(created_user)


# 获取特定用户
@router.get("/{id}")
async def read_user(id: int, db: Session = Depends(get_db)):
    user = user_crud.get(db, id=id)
    if user is None:
        return error("User not found", 404)
    return success(user)


# 更新用户
@router.put("/{id}")
async def update_user(id: int, user_in: UserCreate, db: Session = Depends(get_db)):
    user = user_crud.get(db, id=id)
    if user is None:
        return error("User not found", 404)
    
    updated_user = user_crud.update(db, user, user_in)
    return success(updated_user)


# 删除用户
@router.delete("/{id}")
async def delete_user(id: int, db: Session = Depends(get_db)):
    user = user_crud.get(db, id=id)
    if user is None:
        return error("User not found", 404)
        
    deleted_user = user_crud.delete(db, user)
    return success(deleted_user)